package com.lemlin.network

import androidx.annotation.NonNull
import com.blankj.utilcode.util.LogUtils
import com.lemlin.network.bus.RxBus

open class HttpServiceSubscribe<HttpData : HttpServiceData>(
    private val listener: SubscribeListener<HttpData>
) {

    open fun onStart() {
        listener.onStart()
    }

    open fun onSuccess(resp: HttpData) {
        val value = HttpServiceResponse<HttpData>()
        when (resp.code) {
            200 -> value.apply {
                statusCode = HttpServiceStatus.Status.SUCCESS
                httpData = resp
                listener.onSuccess(resp)
            }
            else -> value.apply {
                statusCode = HttpServiceStatus.Status.FAILURE
                val exception = HttpServiceException.ResponseException(resp.code, resp.msg)
                this.throwable = exception
                listener.onFailure(exception)
            }
        }
    }

    open fun onFailure(@NonNull throwable: Throwable) {
        val value = HttpServiceResponse<HttpServiceData>()
        value.run {
            statusCode = HttpServiceStatus.Status.FAILURE
            val exception: HttpServiceException.ResponseException =
                HttpServiceException.handleThrowable(throwable)
            this.throwable = exception
            listener.onFailure(exception)
        }
    }
}